package com.example.myrsa.controller;

import com.example.myrsa.Service.RSA;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/rsa")
public class RSAController {

    @RequestMapping("/getPrime")
    @ResponseBody
    public String getPrime(String prime){
        System.out.println("prime:"+prime);
        if(prime==null || prime.equals("")){
            Random rand = new Random();
            long longNum = rand.nextLong();
            if (longNum<0)
                longNum = -longNum;
            prime = String.valueOf(longNum);
        }
        return new BigInteger(prime).nextProbablePrime().toString();
    }

    @RequestMapping("/encode")
    @ResponseBody
    public String encode(HttpSession session, String ming, String p, String q, String n, String e, String d){
        Object o = session.getAttribute(p+","+q);
        RSA rsa = null;
        if (o==null){
            rsa = new RSA(new BigInteger(p),new BigInteger(q),new BigInteger(n),new BigInteger(e),new BigInteger(d));
            session.setAttribute(p+","+q,rsa);
        }else{
            rsa  = (RSA)o;
        }
        BigInteger mi = rsa.encode(new BigInteger(ming));
        return mi.toString();
    }

    @RequestMapping("/decode")
    @ResponseBody
    public String decode(HttpSession session, String mi, String p, String q, String n, String e, String d){
        Object o = session.getAttribute(p+","+q);
        RSA rsa = null;
        if (o==null){
            rsa = new RSA(new BigInteger(p),new BigInteger(q),new BigInteger(n),new BigInteger(e),new BigInteger(d));
            session.setAttribute(p+","+q,rsa);
        }else{
            rsa  = (RSA)o;
        }
        BigInteger ming = rsa.decode(new BigInteger(mi));
        return ming.toString();
    }

    @RequestMapping("/getRSANum")
    @ResponseBody
    public Map getRSANum(HttpSession session, String p, String q){
        Object o = session.getAttribute(p+","+q);
        Map map = null;
        if (o==null){
            map = RSA.getRSANum(new BigInteger(p),new BigInteger(q));
        }else{
            RSA t = (RSA)o;
            map = t.returnRSANum();
        }
        return map;
    }
}
